#include "sensor.h"
#include "ESP8266.h"
#include "FreeRTOS.h"
#include "JSON_app.h"
#include "dht11.h"
#include "light.h"
#include "main.h"
// #include "cmsis_os.h"
#include "servo.h"
#include "led.h"
#include "pzem.h"

#include <string.h>
#include <stdio.h>

/**
 * @brief 读取传感器数据并通过 MQTT 发布
 *
 * 该函数会读取 DHT11 传感器的温度和湿度数据，以及光照传感器的亮度数据，
 * 然后将这些数据通过 MQTT 协议发布出去。
 */
bool Get_environment(void)
{
    int hum, temp;
    uint32_t brightness;

    DHT11_Read(&hum, &temp);
    LightSensor_Read(&brightness);
    while (!Energy_assessment());

    DeviceData deviceData = {
        .id = "ESP32_001",
        .power = {0},
        .env = {0},
        .status = {.door = "open", .window = "closed", .light = "on"}};

    if (doorStatus == true)
    {
        strcpy(deviceData.status.door, "open");
    }
    else
    {
        strcpy(deviceData.status.door, "closed");
    }
    if (ledStatus == true)
    {
        strcpy(deviceData.status.light, "on");
    }
    else
    {
        strcpy(deviceData.status.light, "off");
    }
    deviceData.env.tem = temp;
    deviceData.env.hum = hum;
    deviceData.env.lux = brightness;

    extern float Voltage; 
    extern float Current;
    extern float ActivePower;

    deviceData.power.I = Current;
    deviceData.power.U = Voltage;
    deviceData.power.W = ActivePower;

    // 创建并发布JSON
    char *jsonString = CreateDeviceJSON(&deviceData);
    if (jsonString != NULL)
    {
        MQTT_Publish(jsonString);
        cJSON_free(jsonString); // 释放JSON内存
        return true;
    }
    else
    {
        return false;
    }
}
